<template>
	<view>
		<view style="position: sticky; top: 0rpx; left: 0; z-index: 1">
			<view class="search-content">
				<view class="search-content-con">
					<u-search inputAlign="center"
										placeholder="请输入商品名称查询"
										bg-color="#F7F8FA"
										v-model="searchKeyword"
										:height="56"
										:maxlength="20"
										@search="searchInputHandle"
										@custom="searchInputHandle"
										:action-style="searchActionStyle"></u-search>
				</view>
			</view>
			<view style="display: flex; width: 100%">
				<view style="width: 90%"><u-tabs active-color="#ff5510"
									:list="categoryList"
									:is-scroll="true"
									:current="current"
									@change="change"></u-tabs></view>

				<view @click="cardShow = !cardShow"
							class="list-change-bth am-flex-row-center">
					<image class="list-change-bth-img"
								 :src="qieHuanList[cardShow ? 0 : 1]"
								 mode="scaleToFill" />
				</view>
			</view>
			<view>
				<u-tabs active-color="#ff5510"
								:list="secondCategoryList"
								:is-scroll="true"
								:current="secondCurrent"
								@change="secondChange"></u-tabs>
			</view>
		</view>

		<view v-if="dataList.length">
			<view v-for="(list, index) in dataList"
						:key="index">
				<view style="margin: 12rpx 24rpx; margin-top: 0"
							v-if="list.banner && list.banner.length">
					<swiper :indicator-dots="indicatorDots"
									class="swiper"
									style="height: 162rpx"
									:autoplay="autoplay"
									:interval="interval"
									:duration="duration">
						<swiper-item v-for="(item1, ind1) in list.banner"
												 :key="ind1"
												 @click="goDetail(item1)">
							<image class="list-banner-img"
										 :src="item1.imgPath"
										 style="width: 100%; height: 162rpx"
										 :id="'img' + ind1" />
						</swiper-item>
					</swiper>
				</view>
				<view class="products-wrap">
					<view v-for="(item2, index2) in list.dataList"
								:key="index2">
						<goods-card v-if="!cardShow"
												:url="`/pages/goods-details/goods-details?id=${item2.id}`"
												:cover="item2.banner.split(',')[0]"
												:title="item2.name"
												:price="reGoodsPrice(item2)"
												:detail="item2"
												@addCart="addCart"></goods-card>
						<goodsCardSmall v-if="cardShow"
														:url="`/pages/goods-details/goods-details?id=${item2.id}`"
														:cover="item2.banner.split(',')[0]"
														:title="item2.name"
														:price="reGoodsPrice(item2)"
														:detail="item2"
														@addCart="addCart"></goodsCardSmall>
					</view>
				</view>
			</view>
		</view>
		<view style="padding: 8rpx 24rpx"
					v-if="
        dataList.length &&
        dataList[0].dataList &&
        dataList[0].dataList.length < 10 &&
        dataList[0].dataList.length != 0
      ">
			<swiper :indicator-dots="indicatorDots"
							class="swiper"
							style="height: 162rpx"
							:autoplay="autoplay"
							:interval="interval"
							:duration="duration">
				<swiper-item v-for="(item, ind) in listBannerList"
										 :key="item.id"
										 @click="goDetail(item)">
					<image class="list-banner-img"
								 :src="item.imgPath"
								 style="width: 100%; height: 162rpx"
								 :id="'img' + ind"></image>
				</swiper-item>
			</swiper>
		</view>
		<purchaseGoods :showModal="showPay"
									 :detail="goodsData"
									 @close="onclose"
									 @submit="submit"
									 :type="type"></purchaseGoods>
		<co-load-more :type="loadingType"><co-empty slot="empty"
								model="data"
								paddingTop="80rpx"></co-empty></co-load-more>
	</view>
</template>

<script>
import { apiCategoryGoods } from '@/api/goods'
import purchaseGoods from '@/components/purchase-goods/purchase-goods'
import goodsCardSmall from '@/components/goods-card-small/goods-card-small'
import tabbarPage from '@/mixins/tabbarPage'
import { appOnLaunch } from '@/utils/appGlobalLifeCycle'
import RetailPriceSign from './components/retail-price-sign.vue'
import { getList as apiGetList, bannerProxyQueryPage } from '@/api/goods.js'
// 不允许请求的type
const noRequestType = [1, 2, 3]
/**
 * 采用懒更新方案，只有当供应商变了，并且进入当前页面，才会更新数据
 * */
export default {
	data () {
		return {
			goodsData: {},
			categoryList: [],
			shouldUpdate: true, // 是否应该更新
			getLoading: false, // 是否正在刷新列表
			showPay: false,
			type: 1,
			dataList: [],
			searchKeyword: '',
			realSearchKeyword: '',
			searchActionStyle: {
				color: '#fff',
				fontSize: '28rpx',
				background:
					'linear-gradient( 323deg, #FF4564 8%, #F14141 30%, #FC843B 100%)',
				borderRadius: '200rpx 200rpx 200rpx 200rpx',
				width: '112rpx',
				height: '56rpx',
				lineHeight: '56rpx'
			},
			loadingType: 999,
			current: 0,
			secondCurrent: 0,
			categoryIds: [],
			stairCategoryId: '',
			pageNum: 1,
			cardShow: false,
			qieHuanList: [
				'https://kc-glasses-mall-langjing.oss-cn-chengdu.aliyuncs.com/2024/09/23/a03bf10a98cb4fdf89361c311029c9ccqiehuancard.png',
				'https://kc-glasses-mall-langjing.oss-cn-chengdu.aliyuncs.com/2024/09/23/5d4a9f4060874c73b71d012fd27c7184qihuan.png'
			],
			secondCategoryList: [],
			options: {},
			listBannerList: [],
			indicatorDots: true,
			autoplay: true,
			interval: 2000,
			duration: 500
		}
	},
	components: {
		RetailPriceSign,
		purchaseGoods,
		goodsCardSmall
	},
	onLoad (options) {
		this.options = options
		if (this.shouldUpdate && !this.getLoading) {
			this.getProductsList()
			this.getListBannerList()
			// this.unlockInit()
		}
	},
	onShow () {
		if (!this.$store.getters.isLogin) {
			appOnLaunch()
			return
		}
	},
	mixins: [tabbarPage],
	computed: {},
	onReachBottom () {
		this.loadingType = 999
		this.getList()
	},
	methods: {
		getListBannerList () {
			bannerProxyQueryPage({ banner: 1 }).then((res) => {
				console.log(res, '==-=-=--=-')
				if (res.data.code == 200) {
					this.listBannerList = res.data.data
				}
			})
		},
		secondChange (index) {
			this.pageNum = 1
			this.dataList = []
			this.secondCurrent = index
			this.categoryIds = [this.secondCategoryList[index]?.cid] || []
			this.loadingType = 999
			this.getList()
		},
		change (index) {
			this.secondCategoryList = []
			this.categoryIds = []
			this.current = index
			this.secondCurrent = 0
			this.pageNum = 1
			this.dataList = []
			this.stairCategoryId = this.categoryList[index].cid
			this.secondCategoryList =
				index == 0 ? [] : [...(this.categoryList[index]?.categors || [])]
			this.categoryIds = index == 0 ? [] : [this.secondCategoryList[0]?.cid]

			this.loadingType = 999
			this.getList()
		},
		reGoodsPrice (item) {
			return item.skuChildList[0].purchasePrice
		},
		// 搜索框点击搜索
		searchInputHandle (e) {
			console.log(e)
			if (this.realSearchKeyword !== e) {
				this.realSearchKeyword = e
				this.loadingType = 999
				this.unlockInit()
			}
		},
		onclose (show) {
			this.showPay = show
			uni.showTabBar()
		},
		submit (data) {
			uni.showTabBar()
			if (this.type == 1) {
				this.apiAddCart(data)
			} else {
				this.$u.route('pages/place-order/submit-order', {
					val: JSON.stringify(data.val)
				})
			}
			this.showPay = false
		},
		// 启用规格窗口
		addCart (type, val, num) {
			if (num) return
			this.goodsData = val
			this.showPay = true
			uni.hideTabBar()
			this.type = type
		},
		dataInit () {
			this.dataList = []
			this.pageNum = 1
		},
		unlockInit () {
			this.dataInit()
			this.getList()
		},
		getProductsList () {
			if (this.getLoading) return
			this.getLoading = true
			uni.showLoading({
				mask: true
			})
			apiCategoryGoods()
				.then((res) => {
					let { state, data, msg } = res.data
					if (state === 'OK') {
						let categoryList = []

						data[0].categoryEntityVOS.forEach((p1) => {
							categoryList.push({
								cid: p1.cid,
								name: p1.name,
								categors: p1.categors
							})
						})
						this.categoryList = [{ name: '全部', cid: '' }, ...categoryList]
						this.current = Number(this.options.firstIndex) + 1
						console.log(this.options.firstIndex, 'this.options.firstIndex')

						console.log(this.current, 'this.currentthis.current')

						this.secondCurrent = this.options.index || 0
						console.log(this.categoryList, 'this.categoryList')

						this.stairCategoryId = this.options.firstIndex != '-1' ? categoryList[Number(this.options.firstIndex)].cid : ''

						console.log(this.stairCategoryId, 'this.stairCategoryId')

						this.secondCategoryList =
							this.current == 0
								? []
								: [...(this.categoryList[this.current]?.categors || [])]
						this.categoryIds =
							this.current == 0
								? []
								: [this.secondCategoryList[this.secondCurrent]?.cid]
						console.log(" this.getList() this.getList() this.getList()");

						this.getList()
						uni.hideLoading()
						this.shouldUpdate = false
					} else {
						uni.hideLoading()
						this.$am_toast(msg)
					}
					this.getLoading = false
				})
				.catch((err) => {
					console.log(err)
					uni.hideLoading()
					this.getLoading = false
					// this.$am_toast.error('查询失败')
				})
		},
		getList () {
			console.log(
				this.stairCategoryId,
				'this.stairCategoryIdthis.5555555555555555stairCategoryId'
			)

			if (noRequestType.includes(this.loadingType)) {
				return
			}
			this.loadingType = 2
			console.log('调用获取数据')
			console.log(
				this.stairCategoryId,
				'this.stairCategoryIdthis.5555555555555555stairCategoryId'
			)
			apiGetList({
				stairCategoryId: this.stairCategoryId,
				categoryIds: this.categoryIds || [],
				pageNum: this.pageNum,
				pageSize: 10,
				name: this.realSearchKeyword
			})
				.then(({ data }) => {
					console.log(
						this.stairCategoryId,
						'this.stairCategoryIdthis.5555555555555555stairCategoryId'
					)
					if (data.state === 'OK') {
						if (this.pageNum === 1) {
							this.dataList.push({
								banner: [],
								dataList: data.data.list
							})

							// [...this.dataList, ...data.data.list]
						} else {
							this.dataList.push({
								banner: this.listBannerList,
								dataList: data.data.list
							})
						}
						if (this.pageNum === 1 && this.dataList[0]?.dataList?.length == 0) {
							this.loadingType = 1
						} else if (data.data.totalPage == this.pageNum) {
							this.loadingType = 3
						} else {
							this.loadingType = 999
							this.pageNum++
						}
					}
					uni.stopPullDownRefresh()
				})
				.catch((err) => {
					console.log(err)
					this.loadingType = 999
					this.$am_toast.warning('查询失败，请重新尝试！')
					uni.stopPullDownRefresh()
				})
		},
		// 购买
		goBuy (event) {
			let id = event.currentTarget.dataset.pid
			let stock = event.currentTarget.dataset.stockTotal
			if (stock === 0) return
			this.$u.route('pages/place-order/submit-order', { ids: id })
		}
	}
}
</script>

<style lang="scss" scoped>
$product-plr: 16rpx;
.products-wrap {
	display: flex;
	justify-content: space-between;
	flex-wrap: wrap;
	margin: 0 24rpx;
	border-radius: 16rpx;
	&.disabled {
		opacity: 0.5;
	}
}
.product-section-header {
	padding-top: 27rpx;
	padding-left: $product-plr;
	padding-right: $product-plr;
	font-size: 24rpx;
	color: #999999;
}
.search-content {
	display: flex;
	align-items: center;
	padding: 32rpx 24rpx;
	background-color: #fff;
	border-bottom: 2rpx solid #f5f5f5;
}
.search-content-con {
	flex: 1;
}
.list-change-bth {
	width: 10%;
	background: #fff;
	border-left: 1px solid #f5f5f5;
	justify-content: center;
}
.list-change-bth-img {
	width: 40rpx;
	height: 40rpx;
}
.list-banner-img {
	border-radius: 16rpx;
	object-fit: cover;
}
</style>
